/**
 * 增强版银行卡验证器
 * 支持自定义银行信息和标准银行信息的统一验证
 * 作者: AI Assistant
 * 创建时间: 2024
 */

// 导入原有的银行卡验证器
import {
  luhnCheck,
  getBankByBIN,
  standardizeBankName as originalStandardizeBankName,
  validateBankCard as originalValidateBankCard,
  getSupportedBanks,
  formatCardNumber,
  BANK_BIN_MAP,
  BANK_NAME_MAP
} from './bankCardValidator.js'

/**
 * 自定义银行信息管理类
 */
class CustomBankManager {
  constructor() {
    this.customBanks = []
    this.customBinMap = new Map()
    this.customNameMap = new Map()
    this.loadCustomBanks()
    
    // 监听银行信息更新事件
    if (typeof window !== 'undefined') {
      window.addEventListener('bankInfoUpdated', (event) => {
        this.loadCustomBanks()
      })
    }
  }
  
  /**
   * 从本地存储加载自定义银行信息
   */
  loadCustomBanks() {
    try {
      if (typeof localStorage !== 'undefined') {
        const saved = localStorage.getItem('customBankInfo')
        if (saved) {
          this.customBanks = JSON.parse(saved)
          this.buildCustomMaps()
        }
      }
    } catch (error) {
      console.error('加载自定义银行信息失败:', error)
      this.customBanks = []
    }
  }
  
  /**
   * 构建自定义银行的BIN码和名称映射
   */
  buildCustomMaps() {
    this.customBinMap.clear()
    this.customNameMap.clear()
    
    this.customBanks.forEach(bank => {
      const standardName = bank.standardName
      
      // 构建BIN码映射
      if (bank.binCode) {
        this.customBinMap.set(bank.binCode, standardName)
      }
      
      // 构建名称映射
      this.customNameMap.set(standardName.toLowerCase(), standardName)
      
      // 添加简称映射
      if (bank.shortName) {
        this.customNameMap.set(bank.shortName.toLowerCase(), standardName)
      }
      
      // 添加英文简称映射
      if (bank.englishName) {
        this.customNameMap.set(bank.englishName.toLowerCase(), standardName)
      }
      
      // 添加别名映射
      if (bank.aliases && Array.isArray(bank.aliases)) {
        bank.aliases.forEach(alias => {
          this.customNameMap.set(alias.toLowerCase(), standardName)
        })
      }
    })
  }
  
  /**
   * 根据BIN码获取自定义银行信息
   */
  getBankByBIN(bin) {
    const bankName = this.customBinMap.get(bin)
    if (bankName) {
      const bankInfo = this.customBanks.find(b => b.standardName === bankName)
      return {
        name: bankName,
        info: bankInfo
      }
    }
    return null
  }
  
  /**
   * 标准化自定义银行名称
   */
  standardizeBankName(bankName) {
    if (!bankName) return null
    
    const normalized = bankName.trim().toLowerCase()
    return this.customNameMap.get(normalized) || null
  }
  
  /**
   * 获取所有自定义银行列表
   */
  getCustomBanks() {
    return this.customBanks.map(bank => ({
      standardName: bank.standardName,
      shortName: bank.shortName,
      englishName: bank.englishName,
      binCode: bank.binCode,
      cardLengthRule: bank.cardLengthRule,
      aliases: bank.aliases
    }))
  }
  
  /**
   * 验证银行卡号长度是否符合自定义规范
   */
  validateCardLength(cardNumber, bankName) {
    const bank = this.customBanks.find(b => b.standardName === bankName)
    if (!bank || !bank.cardLengthRule) {
      return { valid: true, message: '' }
    }
    
    const cardLength = cardNumber.replace(/\s/g, '').length
    const rule = bank.cardLengthRule
    
    // 解析长度规则，支持格式："16-19位"、"16位"、"16,19位"等
    const lengthPattern = /\d+/g
    const lengths = rule.match(lengthPattern)?.map(Number) || []
    
    if (lengths.length === 0) {
      return { valid: true, message: '' }
    }
    
    let isValid = false
    let expectedLength = ''
    
    if (lengths.length === 1) {
      // 单一长度："16位"
      isValid = cardLength === lengths[0]
      expectedLength = `${lengths[0]}位`
    } else if (lengths.length === 2) {
      // 范围长度："16-19位"
      const [min, max] = lengths.sort((a, b) => a - b)
      isValid = cardLength >= min && cardLength <= max
      expectedLength = `${min}-${max}位`
    } else {
      // 多个可选长度："16,19位"
      isValid = lengths.includes(cardLength)
      expectedLength = lengths.join('或') + '位'
    }
    
    return {
      valid: isValid,
      message: isValid ? '' : `${bankName}银行卡号长度应为${expectedLength}`
    }
  }
}

// 创建自定义银行管理器实例
const customBankManager = new CustomBankManager()

/**
 * 增强版根据BIN码获取银行信息
 * 优先查找自定义银行，然后查找内置银行
 */
export function getBankByBINEnhanced(cardNumber) {
  if (!cardNumber) return null
  
  const cleanCardNumber = cardNumber.replace(/\s/g, '')
  if (cleanCardNumber.length < 6) return null
  
  const bin = cleanCardNumber.substring(0, 6)
  
  // 首先查找自定义银行
  const customBank = customBankManager.getBankByBIN(bin)
  if (customBank) {
    return {
      name: customBank.name,
      isCustom: true,
      info: customBank.info
    }
  }
  
  // 然后查找内置银行
  const builtinBank = getBankByBIN(cardNumber)
  if (builtinBank) {
    return {
      name: builtinBank,
      isCustom: false,
      info: null
    }
  }
  
  return null
}

/**
 * 增强版银行名称标准化
 * 优先匹配自定义银行，然后匹配内置银行
 */
export function standardizeBankNameEnhanced(bankName) {
  if (!bankName) return null
  
  // 首先尝试自定义银行名称标准化
  const customStandardName = customBankManager.standardizeBankName(bankName)
  if (customStandardName) {
    return customStandardName
  }
  
  // 然后尝试内置银行名称标准化
  return originalStandardizeBankName(bankName)
}

/**
 * 增强版银行卡验证
 * 支持自定义银行信息的完整验证
 */
export function validateBankCardEnhanced(cardNumber, bankName) {
  // 基础验证
  if (!cardNumber || !bankName) {
    return {
      valid: false,
      bankMatched: false,
      luhnValid: false,
      message: '请输入银行卡号和银行名称'
    }
  }
  
  const cleanCardNumber = cardNumber.replace(/\s/g, '')
  
  // 银行卡号格式验证
  if (!/^\d{13,19}$/.test(cleanCardNumber)) {
    return {
      valid: false,
      bankMatched: false,
      luhnValid: false,
      message: '银行卡号格式不正确，应为13-19位数字'
    }
  }
  
  // Luhn算法验证
  const luhnValid = luhnCheck(cleanCardNumber)
  if (!luhnValid) {
    return {
      valid: false,
      bankMatched: false,
      luhnValid: false,
      message: '银行卡号校验失败'
    }
  }
  
  // 银行名称标准化
  const standardBankName = standardizeBankNameEnhanced(bankName)
  if (!standardBankName) {
    return {
      valid: false,
      bankMatched: false,
      luhnValid: true,
      message: '不支持的银行名称，请检查输入或添加到自定义银行信息中'
    }
  }
  
  // 根据BIN码获取银行信息
  const bankInfo = getBankByBINEnhanced(cleanCardNumber)
  
  // 银行匹配验证
  let bankMatched = false
  let message = ''
  
  if (bankInfo) {
    bankMatched = bankInfo.name === standardBankName
    if (!bankMatched) {
      message = `银行卡号归属于${bankInfo.name}，与输入的${standardBankName}不匹配`
    }
  } else {
    // 如果BIN码未找到对应银行，但银行名称是有效的，给出提示
    message = `未找到该银行卡号对应的银行信息，请确认卡号是否正确或将银行BIN码添加到自定义银行信息中`
    // 对于自定义银行，如果没有BIN码，我们可以允许通过
    const customBank = customBankManager.customBanks.find(b => b.standardName === standardBankName)
    if (customBank && !customBank.binCode) {
      bankMatched = true
      message = ''
    }
  }
  
  // 自定义银行卡号长度验证
  if (bankMatched && bankInfo && bankInfo.isCustom) {
    const lengthValidation = customBankManager.validateCardLength(cleanCardNumber, standardBankName)
    if (!lengthValidation.valid) {
      return {
        valid: false,
        bankMatched: true,
        luhnValid: true,
        message: lengthValidation.message
      }
    }
  }
  
  const valid = luhnValid && bankMatched
  
  return {
    valid,
    bankMatched,
    luhnValid,
    message: valid ? '银行卡验证通过' : message,
    standardBankName,
    bankInfo: bankInfo ? {
      name: bankInfo.name,
      isCustom: bankInfo.isCustom,
      customInfo: bankInfo.info
    } : null
  }
}

/**
 * 获取所有支持的银行列表（内置 + 自定义）
 */
export function getAllSupportedBanks() {
  const builtinBanks = getSupportedBanks().map(name => ({
    name,
    isCustom: false
  }))
  
  const customBanks = customBankManager.getCustomBanks().map(bank => ({
    name: bank.standardName,
    isCustom: true,
    shortName: bank.shortName,
    englishName: bank.englishName,
    binCode: bank.binCode,
    cardLengthRule: bank.cardLengthRule,
    aliases: bank.aliases
  }))
  
  return {
    builtin: builtinBanks,
    custom: customBanks,
    all: [...builtinBanks, ...customBanks]
  }
}

/**
 * 搜索银行信息
 */
export function searchBanks(keyword) {
  if (!keyword) return getAllSupportedBanks().all
  
  const lowerKeyword = keyword.toLowerCase()
  const allBanks = getAllSupportedBanks()
  
  return allBanks.all.filter(bank => {
    // 搜索标准名称
    if (bank.name.toLowerCase().includes(lowerKeyword)) {
      return true
    }
    
    // 搜索自定义银行的其他字段
    if (bank.isCustom) {
      return (
        (bank.shortName && bank.shortName.toLowerCase().includes(lowerKeyword)) ||
        (bank.englishName && bank.englishName.toLowerCase().includes(lowerKeyword)) ||
        (bank.binCode && bank.binCode.includes(keyword)) ||
        (bank.aliases && bank.aliases.some(alias => alias.toLowerCase().includes(lowerKeyword)))
      )
    }
    
    return false
  })
}

/**
 * 获取银行详细信息
 */
export function getBankDetails(bankName) {
  const standardName = standardizeBankNameEnhanced(bankName)
  if (!standardName) return null
  
  // 查找自定义银行
  const customBank = customBankManager.customBanks.find(b => b.standardName === standardName)
  if (customBank) {
    return {
      standardName: customBank.standardName,
      shortName: customBank.shortName,
      englishName: customBank.englishName,
      binCode: customBank.binCode,
      cardLengthRule: customBank.cardLengthRule,
      aliases: customBank.aliases,
      isCustom: true
    }
  }
  
  // 查找内置银行
  const builtinBanks = getSupportedBanks()
  if (builtinBanks.includes(standardName)) {
    return {
      standardName,
      isCustom: false
    }
  }
  
  return null
}

/**
 * 重新加载自定义银行信息
 */
export function reloadCustomBanks() {
  customBankManager.loadCustomBanks()
}

/**
 * 获取自定义银行管理器实例（用于高级操作）
 */
export function getCustomBankManager() {
  return customBankManager
}

// 导出原有的工具函数
export {
  luhnCheck,
  formatCardNumber,
  getSupportedBanks
}

// 导出原有的数据映射（用于兼容性）
export {
  BANK_BIN_MAP,
  BANK_NAME_MAP
}

// 默认导出增强版验证函数
export default {
  validateBankCard: validateBankCardEnhanced,
  standardizeBankName: standardizeBankNameEnhanced,
  getBankByBIN: getBankByBINEnhanced,
  getAllSupportedBanks,
  searchBanks,
  getBankDetails,
  reloadCustomBanks,
  luhnCheck,
  formatCardNumber
}